"use strict";
// Class definition

var projectDivision = function () {

    var nodeTypes = [
        {
            name: '单位工程',
            icon: 'unit-engineering',
        },
        {
            name: '子单位工程',
            icon: 'sub-unit-project',
        },
        {
            name: '分部工程',
            icon: 'division-engineering',
        },
        {
            name: '分项工程',
            icon: 'subentry-engineering',
        },
        {
            name: '检验批',
            icon: 'inspection-approval',
        }
    ];
    var $table = $('#tree-table');

    var eventHandler = function () {
        $(document).off('click', '.preview-division');
        $(document).on('click', '.preview-division', previewDivision);

        $(document).off('click', '.save-btn');
        $(document).on('click', '.save-btn', saveDivision);
    };

    /**
     * 预览工程划分
     * @param e
     */
    var previewDivision = function (e) {
        e.preventDefault();
        var theadData = getTheadData();
        var tbodyData = KBsTTExt.getPreviewData($table);
        var previewTable = getPreviewTable({
            theadData: theadData,
            tbodyData: tbodyData
        });
        var $previewModal =  $('#preview-project-division');
        $previewModal.find('.modal-body').html(previewTable);
        $previewModal.modal('show');
    };

    /**
     * 工程划分表单验证
     * @param callback
     */
    function validateForm(callback) {
        var $validateForm = $('#project-division-form');
        $validateForm.validate({
            // define validation rules
            rules: {
                belongsProject: {
                    required: true
                },
                projectName: {
                    required: true
                },
                subProjectName: {
                    required: true
                },
                subProjectNum: {
                    required: true
                }
            },
            messages: {
                belongsProject: {
                    required: '请选择所属项目!'
                },
                projectName: {
                    required: '请选择工程名称!'
                },
                subProjectName: {
                    required: '请输入工程名称!'
                },
                subProjectNum: {
                    required: '请输入工程编号!'
                }
            },

            //display error alert on form submit
            invalidHandler: function(event, validator) {
                if (validator.errorList.length > 0) {
                    $(validator.errorList[0].element).focus();
                }
            },

            submitHandler: callback
        });

        $validateForm.submit();
    }

    /**
     * 保存工程划分
     */
    function saveDivision(e) {
        e.preventDefault();
        validateForm(function () {
            var tableData = KBsTTExt.getPreviewData($table);
            console.log(tableData);
        });
    }

    /**
     * 获取表头数据
     * @returns {{}}
     */
    function getTheadData() {
        var theadData = {};
        theadData.belongsProject = $('[name="belongsProject"]').val();
        theadData.projectName = $('[name="projectName"]').val();
        return theadData;
    }

    /**
     * 获取表格行
     * @param rows
     * @param previewTable
     * @returns {*}
     */
    function getTbodyRows(rows, previewTable) {
        rows.forEach(function (row, index) {
            if (row.lv === 1) {
                previewTable += '<tr>';
            }

            if (row.num) {
                previewTable += '<td rowspan="'+ row.rowspan +'">'+ row.num +'</td>';
            }
            previewTable += '<td rowspan="'+ row.rowspan +'" data-level="'+ row.lv +'">'+ row.subProjectName +'</td>';
            previewTable += '<td rowspan="'+ row.rowspan +'">'+ row.subProjectNum+'</td>';
            if (row.children.length > 0) {
                previewTable = getTbodyRows(row.children, previewTable);
            }

            if (row.lv === nodeTypes.length) {
                previewTable += '</tr>';
                previewTable += '<tr>';
            }

            if (row.lv === 1) {
                previewTable += '</tr>';
            }
        });


        return previewTable;
    }

    /**
     * 获取预览表格
     * @param previewData
     * @returns {string}
     */
    var getPreviewTable = function (previewData) {
        var totalColspan = nodeTypes.length * 2 + 1;
        var previewTable = '<table border="1" cellspacing="0" class="preview-table table table-bordered" width="95%" align="center" valign="middle">';
        if (previewData.theadData) {
            previewTable += '<thead>';
            previewTable += '<tr>';
            previewTable += '<th colspan="2">所属项目</th>';
            previewTable += '<th colspan="2">' + previewData.theadData.belongsProject + '</th>';
            previewTable += '<th>工程名称</th>';
            previewTable += '<th colspan="' + (totalColspan - 5) + '">' + previewData.theadData.projectName + '</th>';
            previewTable += '</tr>';
            previewTable += '<tr>';
            previewTable += '<th>序号</th>';
            nodeTypes.forEach(function (nodeType, index) {
                previewTable += '<th>' + nodeType.name + '</th>';
                previewTable += '<th>工程编号</th>';
            });
            previewTable += '</tr>';
            previewTable += '</thead>';
        }
        if (previewData.tbodyData) {
            previewTable += '<tbody>';
            previewTable = getTbodyRows(previewData.tbodyData, previewTable);
            previewTable += '</tbody>';
        }

        previewTable += '</table>';
        return previewTable;
    }

    var initBaseInfo = function () {
        $('.k_selectpicker').selectpicker();
    };

    /**
     * 检查是否可以删除指定行
     * @param row
     * @returns {Promise<*>}
     */
    var checkDelAble = async function (row) {
        var params = {
            id: row.id
        };

        var delAble = false;
        var res = await KHttp.get('/default/json/project-base-info/construction-project/check-deletable.json', params);
        if (res && res.data) {
            delAble = res.data;
        }

        if (!delAble) {
            KDatacom.swal({
                title: '警告！',
                text: "该工程划分下已关联施工资料，请联系管理员删除!",
                type: 'warning'
            });
        }

        return delAble;
    };

    var initTreeTable = async function () {
        var editable = true;
        var options = {
            editable: editable,
            nodeTypes: nodeTypes,
            checkDelAble: checkDelAble,
            columns: [
                {
                    checkbox: true
                }, {
                    title: '工程名称',
                    field: 'subProjectName',
                    width: '55%',
                    align: "left",
                    treeNode: true,
                    editable: true,
                },
                {
                    field: 'subProjectNum',
                    title: '工程编号',
                    width: '20%',
                    align: "left",
                    editable: true
                },
                {
                    field: 'lv',
                    title: '类型',
                    width: '10%',
                    formatter: function (value, row, index) {
                        var typeName = nodeTypes[value - 1].name;
                        var type = '';
                        if (value === 1) {
                            type = '<span class="badge badge-primary">' + typeName + '</span>'
                        } else if (value === 2) {
                            type = '<span class="badge badge-secondary">' + typeName + '</span>'
                        } else if (value === 3) {
                            type = '<span class="badge badge-success">' + typeName + '</span>'
                        } else if (value === 4) {
                            type = '<span class="badge badge-danger">' + typeName + '</span>'
                        } else if (value === 5) {
                            type = '<span class="badge badge-info">' + typeName + '</span>'
                        } else {
                            type = '<span class="badge badge-dark">' + typeName + '</span>'
                        }
                        return type;
                    }
                },
                {
                    title: '操作',
                    width: '10%',
                    formatter: function (value, row, index) {
                        var actions = [];
                        if (row.lv < nodeTypes.length) {
                            actions.push('<a class="add-node-row" href="#">新增下级</a> ');
                        }

                        actions.push('<a class="delete-node-row" href="#" >删除</a>');
                        return actions.join('');
                    }
                }
            ]
        };

        //TODO 编辑模式需单独获取数据
        if (editable) {
            var res = await KHttp.get('/default/json/project-base-info/construction-project/khttp-project-division.json');
            options.data = res && res.data ? res.data : [];
            //TODO 查看模式可直接传入url
        } else {
            options.url = '/default/json/project-base-info/construction-project/project-division.json';
        }

        var treeTable = KBsTTExt.init(options, $table);
    };

    return {
        // public functions
        init: function () {
            eventHandler();
            initBaseInfo();
            initTreeTable();
        }
    };
}();

jQuery(document).ready(function () {
    projectDivision.init();
});
